package main

import (
	"fmt"
	jsoniter "github.com/json-iterator/go"
	"github.com/savsgio/atreugo/v11"
	"path"
	"time"
)

type WebFrame struct {
	Id      int64
	Name    string
	Version string
	Birth   time.Time
	Author  string
}

func main() {
	config := atreugo.Config{
		Addr: "0.0.0.0:2001",
	}
	server := atreugo.New(config)

	server.GET("/", func(ctx *atreugo.RequestCtx) error {
		return ctx.TextResponse("Hello World")
	})

	server.GET("/echo/{path:*}", func(ctx *atreugo.RequestCtx) error {
		return ctx.TextResponse("Echo message: " + ctx.UserValue("path").(string))
	})

	server.GET("/atreugo/parms", func(ctx *atreugo.RequestCtx) error {
		name := string(ctx.FormValue("name"))
		fmt.Println(name)
		age := string(ctx.FormValue("age"))
		fmt.Println(age)
		sex := string(ctx.FormValue("sex"))
		fmt.Println(sex)

		return ctx.JSONResponse(map[string]interface{}{"code": 200, "message": "成功"})
	})

	server.POST("/atreugo/form", func(ctx *atreugo.RequestCtx) error {
		name := string(ctx.FormValue("name"))
		fmt.Println(name)
		age := string(ctx.FormValue("age"))
		fmt.Println(age)

		return ctx.JSONResponse(map[string]interface{}{"code": 200, "message": "成功"})
	})

	server.POST("/atreugo/json", func(ctx *atreugo.RequestCtx) error {
		var wf WebFrame
		wfByte := ctx.PostBody()
		dErr := jsoniter.ConfigCompatibleWithStandardLibrary.Unmarshal(wfByte, &wf)
		if dErr != nil {
			return ctx.JSONResponse(map[string]interface{}{"code": 500, "message": dErr.Error()})
		}

		fmt.Println("wf：", wf)
		return ctx.JSONResponse(map[string]interface{}{"code": 200, "message": "成功"})
	})

	v1 := server.NewGroupPath("/v1")
	v1.GET("/", func(ctx *atreugo.RequestCtx) error {
		return ctx.TextResponse("Hello V1 Group")
	})

	server.GET("/file", func(ctx *atreugo.RequestCtx) error {
		id := string(ctx.FormValue("id"))
		fmt.Println(id)

		ctx.SendFile("E:/Chrome/TestReport202203030410.html")

		return nil
	})

	//server.ServeFile("/download", "F:/hot_change/android/98e536200ff4465a110a86103a02249f.apk")

	server.GET("/download", func(ctx *atreugo.RequestCtx) error {

		filePath := "F:/hot_change/android/98e536200ff4465a110a86103a02249f.apk"

		//获取文件的名称
		fileName := path.Base(filePath)

		ctx.SetContentType("aContent-Disposition")
		//强制浏览器下载
		ctx.Response.Header.Set("Content-Disposition", "attachment; filename="+fileName)
		//浏览器下载或预览
		ctx.Response.Header.Set("Content-Disposition", "inline;filename="+fileName)
		ctx.Response.Header.Set("Content-Transfer-Encoding", "binary")
		ctx.Response.Header.Set("Cache-Control", "no-cache")

		//ctx.FileResponse("98e536200ff4465a110a86103a02249f.apk", "F:/hot_change/android/", "aContent-Disposition")

		ctx.SendFile(filePath)

		return nil
	})

	if err := server.ListenAndServe(); err != nil {
		panic(err)
	}
}
